(function(){
  'use strict';

  var SELECT = document.getElementById('bind-connector-select');
  var HIDDEN_INPUT = document.getElementById('bind-connector');
  var FIELDS_WRAP = document.getElementById('bind-cred-fields');
  var JSON_TEXTAREA = null; // 页面已去除该区域
  var SUBMIT_BTN = document.getElementById('bind-submit');
  var ACCOUNT_INPUT = document.getElementById('bind-account');
  var MSG = document.getElementById('bind-msg');

  if (!SELECT || !FIELDS_WRAP) {
    console.log('ConnectorUI: 缺少必要元素', { SELECT: !!SELECT, FIELDS_WRAP: !!FIELDS_WRAP });
    return;
  }
  
  console.log('ConnectorUI: 开始初始化');

  var KEYS_URL = 'exports/connector_credentials_keys.v2.json';
  var keysMap = null; // {connector: [keys]}

  // 交易所中英文对照和logo映射（使用真实logo）
  var exchangeMap = {
    'binance': { cn: '币安', en: 'Binance', logo: 'binance.png' },
    'binance_us': { cn: '币安美国', en: 'Binance US', logo: 'binance.png' },
    'gate': { cn: '芝麻开门', en: 'Gate.io', logo: 'gateio.png' },
    'gate_io': { cn: '芝麻开门', en: 'Gate.io', logo: 'gateio.png' },
    'okx': { cn: '欧易', en: 'OKX', logo: 'okx.png' },
    'huobi': { cn: '火币', en: 'Huobi', logo: 'huobi.png' },
    'htx': { cn: '火币HTX', en: 'HTX', logo: 'huobi.png' },
    'kraken': { cn: '海妖', en: 'Kraken', logo: 'kraken.png' },
    'coinbase': { cn: 'Coinbase', en: 'Coinbase', logo: 'coinbase.png' },
    'coinbase_advanced_trade': { cn: 'Coinbase高级', en: 'Coinbase Advanced', logo: 'coinbase.png' },
    'mexc': { cn: '抹茶', en: 'MEXC', logo: 'mexc.png' },
    'bingx': { cn: '必应', en: 'BingX', logo: 'bingx.png' },
    'bing_x': { cn: '必应', en: 'BingX', logo: 'bingx.png' },
    'bitmart': { cn: '比特玛特', en: 'BitMart', logo: 'bitmart.png' },
    'bitrue': { cn: '比特真', en: 'Bitrue', logo: 'bitrue.png' },
    'bitstamp': { cn: 'Bitstamp', en: 'Bitstamp', logo: 'bitstamp.png' },
    'vertex': { cn: 'Vertex', en: 'Vertex', logo: 'vertex-protocol.png' },
    'injective': { cn: 'Injective', en: 'Injective', logo: 'injective.png' },
    'injective_v2': { cn: 'Injective V2', en: 'Injective V2', logo: 'injective.png' },
    'ndax': { cn: 'NDAX', en: 'NDAX', logo: 'ndax.png' },
    'bybit': { cn: 'Bybit', en: 'Bybit', logo: 'bybit.png' },
    'kucoin': { cn: '库币', en: 'KuCoin', logo: 'kucoin.png' },
    'kucoin_hft': { cn: '库币HFT', en: 'KuCoin HFT', logo: 'kucoin.png' },
    'bitget': { cn: 'Bitget', en: 'Bitget', logo: 'bitget.png' },
    'crypto_com': { cn: 'Crypto.com', en: 'Crypto.com', logo: 'crypto-dot-com.png' },
    'ascend_ex': { cn: 'AscendEX', en: 'AscendEX', logo: 'ascendex.png' },
    'btc_markets': { cn: 'BTC Markets', en: 'BTC Markets', logo: 'btcmarkets.png' },
    'cube': { cn: 'Cube', en: 'Cube', logo: 'ascendex.png' },
    'hyperliquid': { cn: 'Hyperliquid', en: 'Hyperliquid', logo: 'hyperliquid.png' },
    'derive': { cn: 'Deriv', en: 'Deriv', logo: 'binance.png' },
    'dexalot': { cn: 'Dexalot', en: 'Dexalot', logo: 'binance.png' },
    'foxbit': { cn: 'Foxbit', en: 'Foxbit', logo: 'binance.png' },
    'dydx': { cn: 'dYdX', en: 'dYdX', logo: 'dydx.png' },
    'dydx_v4': { cn: 'dYdX V4', en: 'dYdX V4', logo: 'dydx.png' },
    'xrpl': { cn: 'XRP账本', en: 'XRP Ledger', logo: 'xrp.png' }
  };

  function normalizeBrand(name){
    var n = String(name||'').toLowerCase();
    n = n.replace(/_perpetual(_testnet)?$/,'');
    n = n.replace(/_testnet$/,'');
    // unify gate_io -> gate, bing_x -> bingx
    if (n === 'gate_io') return 'gate';
    if (n === 'gate') return 'gate';
    if (n === 'bing_x') return 'bingx';
    return n;
  }

  function getExchangeDisplay(brand) {
    var normalized = normalizeBrand(brand);
    var info = exchangeMap[normalized];
    if (info) {
      return info.cn + ' (' + info.en + ')';
    }
    return brand; // 默认显示
  }

  function getExchangeLogo(brand) {
    var normalized = normalizeBrand(brand);
    var info = exchangeMap[normalized];
    return info ? info.logo : null;
  }

  function enhanceSelectWithLogos() {
    // 创建自定义下拉选择器，支持logo显示
    var selectWrap = SELECT.parentElement;
    if (!selectWrap) return;
    
    // 检查是否已经创建了自定义选择器
    if (selectWrap.querySelector('.custom-select')) return;
    
    // 隐藏原生select
    SELECT.style.display = 'none';
    
    // 创建自定义选择器容器
    var customSelect = document.createElement('div');
    customSelect.className = 'custom-select';
    customSelect.style.cssText = 'position:relative;width:100%;';
    
    // 创建选中项显示区域
    var selectedDisplay = document.createElement('div');
    selectedDisplay.className = 'custom-select-selected';
    selectedDisplay.style.cssText = 'width:100%;height:44px;padding:10px 40px 10px 12px;border-radius:10px;border:1px solid rgba(15,23,42,.12);background:#fff;color:#0f172a;cursor:pointer;display:flex;align-items:center;gap:8px;position:relative;';
    selectedDisplay.innerHTML = '<span style="color:#94a3b8;">请选择交易所</span>';
    
    // 添加下拉箭头
    var arrow = document.createElement('span');
    arrow.className = 'custom-select-arrow';
    arrow.style.cssText = 'position:absolute;right:12px;top:50%;transform:translateY(-50%);width:12px;height:12px;pointer-events:none;transition:transform 0.2s;';
    arrow.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12"><path fill="#334155" d="M6 8L2 4h8z"/></svg>';
    selectedDisplay.appendChild(arrow);
    
    // 创建下拉选项列表
    var optionsList = document.createElement('div');
    optionsList.className = 'custom-select-options';
    optionsList.style.cssText = 'display:none;position:absolute;top:100%;left:0;right:0;max-height:300px;overflow-y:auto;background:#fff;border:1px solid rgba(15,23,42,.12);border-radius:10px;margin-top:4px;box-shadow:0 4px 12px rgba(2,6,23,.08);z-index:1000;';
    
    // 填充选项
    for (var i = 0; i < SELECT.options.length; i++) {
      var option = SELECT.options[i];
      var optionDiv = document.createElement('div');
      optionDiv.className = 'custom-select-option';
      optionDiv.style.cssText = 'padding:10px 12px;cursor:pointer;display:flex;align-items:center;gap:8px;transition:background 0.15s;';
      optionDiv.setAttribute('data-value', option.value);
      
      var logoFile = option.getAttribute('data-logo');
      if (logoFile && option.value) {
        var logoImg = document.createElement('img');
        logoImg.src = 'assets/icons/exchanges/' + logoFile;
        logoImg.style.cssText = 'width:20px;height:20px;object-fit:contain;border-radius:4px;flex-shrink:0;';
        optionDiv.appendChild(logoImg);
      }
      
      var textSpan = document.createElement('span');
      textSpan.textContent = option.text;
      textSpan.style.cssText = option.value ? 'color:#0f172a;' : 'color:#94a3b8;';
      optionDiv.appendChild(textSpan);
      
      // 悬停效果
      optionDiv.addEventListener('mouseenter', function() {
        this.style.background = 'rgba(14,165,233,.08)';
      });
      optionDiv.addEventListener('mouseleave', function() {
        this.style.background = '';
      });
      
      // 点击选择
      (function(opt, val, txt, logo) {
        optionDiv.addEventListener('click', function() {
          SELECT.value = val;
          
          // 更新显示
          selectedDisplay.innerHTML = '';
          if (logo && val) {
            var img = document.createElement('img');
            img.src = 'assets/icons/exchanges/' + logo;
            img.style.cssText = 'width:20px;height:20px;object-fit:contain;border-radius:4px;flex-shrink:0;';
            selectedDisplay.appendChild(img);
          }
          var span = document.createElement('span');
          span.textContent = txt;
          span.style.cssText = val ? 'color:#0f172a;' : 'color:#94a3b8;';
          selectedDisplay.appendChild(span);
          selectedDisplay.appendChild(arrow);
          
          // 触发change事件
          var event = new Event('change', { bubbles: true });
          SELECT.dispatchEvent(event);
          
          // 关闭下拉列表
          optionsList.style.display = 'none';
          arrow.style.transform = 'translateY(-50%)';
        });
      })(option, option.value, option.text, logoFile);
      
      optionsList.appendChild(optionDiv);
    }
    
    // 点击显示区域切换下拉列表
    selectedDisplay.addEventListener('click', function(e) {
      e.stopPropagation();
      var isOpen = optionsList.style.display === 'block';
      optionsList.style.display = isOpen ? 'none' : 'block';
      arrow.style.transform = isOpen ? 'translateY(-50%)' : 'translateY(-50%) rotate(180deg)';
    });
    
    // 点击外部关闭下拉列表
    document.addEventListener('click', function() {
      optionsList.style.display = 'none';
      arrow.style.transform = 'translateY(-50%)';
    });
    
    customSelect.appendChild(selectedDisplay);
    customSelect.appendChild(optionsList);
    selectWrap.insertBefore(customSelect, SELECT);
  }

  function isTestnet(conn){ return /testnet/i.test(conn); }

  function groupByBrand(map){
    var grouped = {}; // { brand: { spot: connName|undefined, perp: connName|undefined } }
    var names = Object.keys(map||{});
    for (var i=0;i<names.length;i++){
      var c = names[i];
      if (isTestnet(c)) continue;
      var brand = normalizeBrand(c);
      var entry = grouped[brand] || { brand: brand, spot: null, perp: null };
      if (/perpetual/i.test(c) || /_perp/.test(c)) entry.perp = c; else entry.spot = c;
      grouped[brand] = entry;
    }
    return grouped; // brand -> {brand, spot, perp}
  }

  function normalizeKeyBase(k){
    var s = String(k||'').toLowerCase();
    var parts = s.split('_');
    if (parts.length>=2){
      var last2 = parts.slice(-2).join('_');
      var last1 = parts[parts.length-1];
      if (/(api_key|api_secret|secret_key|passphrase|memo|uid|user_id|sub_id|subaccount_id|group_id|api_tier|private_key|chain_address|address)$/.test(last2)) return last2;
      return last1;
    }
    return s;
  }

  function cnAlias(k){
    var base = normalizeKeyBase(k);
    var dict = {
      'api_key':'API Key',
      'api_secret':'API Secret',
      'secret_key':'Secret Key',
      'passphrase':'交易口令/Passphrase',
      'memo':'备注/Memo 或 Tag',
      'uid':'用户ID/UID',
      'user_id':'用户ID',
      'sub_id':'子账户标识',
      'subaccount_id':'子账户ID',
      'group_id':'分组ID',
      'api_tier':'API 等级',
      'private_key':'私钥',
      'chain_address':'链上地址',
      'address':'地址'
    };
    return dict[base] || '凭证';
  }

  function validate(k, v){
    var val = String(v||'').trim(); if (!val) return '必填项';
    var L = val.length; var kk = String(k||'').toLowerCase();
    if (/(secret|private|token|pass|api_key|api_secret|secret_key)/.test(kk) && L < 6) return '长度过短';
    if (/(address)/.test(kk) && L < 8) return '地址过短';
    return '';
  }

  function renderFields(keys){
    FIELDS_WRAP.innerHTML = '';
    // keys is array of objects: { repKey, base }
    for (var j=0;j<keys.length;j++){
      var rep = keys[j]; var key = rep.repKey; var base = rep.base;
      var wrap = document.createElement('div'); wrap.className = 'field';
      var label = document.createElement('label'); label.textContent = cnAlias(base) + '（' + key + '）';
      var input = document.createElement('input'); input.className = 'input';
      input.placeholder = /(secret|pass)/i.test(key) ? '****' : key; input.setAttribute('data-cred-key', key); input.setAttribute('data-base', base);
      var err = document.createElement('div'); err.className = 'small'; err.style.color = '#dc2626'; err.setAttribute('data-err', key);
      wrap.appendChild(label); wrap.appendChild(input); wrap.appendChild(err); FIELDS_WRAP.appendChild(wrap);
      input.addEventListener('input', syncState);
    }
    // hint
    var hint = document.createElement('p'); hint.className = 'muted small'; hint.textContent = '提示：请在交易所后台为现货与合约同时开启 API 权限；若合约需要额外字段（如用户ID），请一并填写。';
    FIELDS_WRAP.appendChild(hint);
    syncState();
  }

  function collect(){
    var byKey = {}; var byBase = {};
    var inputs = FIELDS_WRAP.querySelectorAll('input[data-cred-key]');
    for (var i=0;i<inputs.length;i++){
      var el = inputs[i]; var k = el.getAttribute('data-cred-key')||''; var b = el.getAttribute('data-base')||''; var v = (el.value||'').trim();
      if (k) byKey[k] = v; if (b) byBase[b] = v;
    }
    return { byKey: byKey, byBase: byBase };
  }

  function allFilled(values){
    var ks = Object.keys(values); if (!ks.length) return false; for (var i=0;i<ks.length;i++){ if (!values[ks[i]]) return false; } return true;
  }

  function syncState(){
    var values = collect();
    // show errors
    var inputs = FIELDS_WRAP.querySelectorAll('input[data-cred-key]');
    for (var i=0;i<inputs.length;i++){
      var el = inputs[i]; var k = el.getAttribute('data-cred-key')||''; var b = el.getAttribute('data-base')||''; var msg = validate(b||k, el.value);
      var err = FIELDS_WRAP.querySelector('[data-err="'+k+'"]'); if (err) err.textContent = msg;
      if (msg) el.setAttribute('aria-invalid','true'); else el.removeAttribute('aria-invalid');
    }
    // 页面已移除 JSON 文本域
    var brand = SELECT ? (SELECT.value||'').trim() : '';
    SUBMIT_BTN && (SUBMIT_BTN.disabled = !(brand && allFilled(values.byBase)));
  }

  async function load(){
    console.log('ConnectorUI: 开始加载交易所数据');
    try{
      var res = await fetch(KEYS_URL, { cache: 'no-cache' });
      if (!res.ok) throw new Error('HTTP '+res.status);
      keysMap = await res.json();
      console.log('ConnectorUI: 成功加载交易所数据', keysMap);
    }catch(err){ 
      console.error('ConnectorUI: 加载交易所数据失败', err);
      keysMap = {}; 
    }

    var grouped = groupByBrand(keysMap);

    // Render select: one item per brand only
    SELECT.innerHTML = '';
    var opt0 = document.createElement('option'); 
    opt0.value=''; 
    opt0.text='请选择交易所'; 
    opt0.setAttribute('data-logo', '');
    SELECT.appendChild(opt0);
    
    var brands = Object.keys(grouped).sort();
    for (var i=0;i<brands.length;i++){
      var b = brands[i]; 
      var opt = document.createElement('option'); 
      opt.value = b; 
      opt.text = getExchangeDisplay(b);
      var logo = getExchangeLogo(b);
      if (logo) opt.setAttribute('data-logo', logo);
      SELECT.appendChild(opt);
    }

    function planForBrand(brand){
      var entry = grouped[brand] || {};
      var spotKeys = (entry.spot && keysMap[entry.spot]) || [];
      var perpKeys = (entry.perp && keysMap[entry.perp]) || [];
      var byBase = {};
      for (var i=0;i<spotKeys.length;i++){ var k=spotKeys[i]; var b=normalizeKeyBase(k); if (!byBase[b]) byBase[b] = k; }
      for (var j=0;j<perpKeys.length;j++){ var k2=perpKeys[j]; var b2=normalizeKeyBase(k2); if (!byBase[b2]) byBase[b2] = k2; }
      var fields = []; var bases = Object.keys(byBase);
      for (var t=0;t<bases.length;t++){ fields.push({ repKey: byBase[bases[t]], base: bases[t] }); }
      return { fields: fields, entry: entry };
    }

    // 先添加change事件监听器
    SELECT.addEventListener('change', function(){
      var brand = SELECT.value || '';
      // keep hidden input for backward compat
      if (HIDDEN_INPUT) HIDDEN_INPUT.value = brand;
      var plan = planForBrand(brand);
      renderFields(plan.fields);
    });
    
    // 然后再增强select显示
    enhanceSelectWithLogos();

    // submit handler: bind spot and perp with same credentials
    var form = document.getElementById('form-bind');
    if (form){
      function buildCombinedCredentials(entry, values){
        var union = [];
        var seen = {};
        var spot = entry.spot ? (keysMap[entry.spot] || []) : [];
        var perp = entry.perp ? (keysMap[entry.perp] || []) : [];
        for (var i=0;i<spot.length;i++){ var k=spot[i]; if(!seen[k]){ seen[k]=true; union.push(k);} }
        for (var j=0;j<perp.length;j++){ var k2=perp[j]; if(!seen[k2]){ seen[k2]=true; union.push(k2);} }
        var out = {};
        for (var t=0;t<union.length;t++){
          var key = union[t]; var base = normalizeKeyBase(key);
          var val = values.byBase[base]; if (val == null) val = values.byKey[key];
          if (val != null && String(val).length>0) out[key] = val;
        }
        return out;
      }

      form.addEventListener('submit', async function(ev){
        ev.preventDefault(); if (!window.AppApi) return;
        var brand = SELECT.value || '';
        var entry = grouped[brand] || {};
        var account = (ACCOUNT_INPUT && ACCOUNT_INPUT.value) || '';
        var creds = collect();
        if (!brand || !allFilled(creds.byBase) || !account){ return; }
        MSG && (MSG.textContent = '提交中...');
        try{
          // 统一一次提交：connector_name 使用现货（若无现货则用合约）
          var connectorName = entry.spot || entry.perp || brand;
          var combined = buildCombinedCredentials(entry, creds);
          
          // 使用正确的API路径和参数格式
          var credentialsPayload = { 
            account_name: account, 
            connector_name: connectorName, 
            credentials: combined 
          };
          
          console.log('绑定交易所凭据请求参数:', credentialsPayload);
          var response = await window.AppApi.request('POST','/users/accounts/credentials', credentialsPayload, true);
          console.log('绑定API响应状态:', response.status, response.ok);
          var responseData = await window.AppApi.jsonOrThrow(response);
          console.log('绑定API响应数据:', responseData);
          MSG && (MSG.textContent = '提交成功');
          
          // 绑定成功后刷新数据
          if (window.loadSettingsData && typeof window.loadSettingsData === 'function') {
            console.log('绑定成功，刷新设置页面数据...');
            setTimeout(function() {
              window.loadSettingsData();
            }, 1000);
          }
        }catch(err){ MSG && (MSG.textContent = '失败：' + (err && err.message ? err.message : '未知错误')); }
      });
    }
  }

  // expose small helpers for debug
  window.ConnectorUIModule = { load: load };
  load();
})();
